package com.batman.baselibrary.image;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.batman.baselibrary.R;
import com.batman.baselibrary.base.BaseActivity;
import com.batman.baselibrary.utils.BitmapUtil;
import com.batman.baselibrary.utils.Utils;
import com.batman.baselibrary.widget.ImagePreviewView;
import com.batman.baselibrary.widget.Loading;
import com.batman.baselibrary.widget.PreviewerViewPager;

import java.io.File;
import java.util.concurrent.Future;

/**
 * 作者：yuhb on 2019-11-11 20:53.
 * 描述：
 */
public class ImageGalleryActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    public static final String KEY_IMAGE = "images";
    public static final String KEY_COOKIE = "cookie_need";
    public static final String KEY_POSITION = "position";
    public static final String KEY_NEED_SAVE = "save";
    private PreviewerViewPager mImagePager;
    private TextView mIndexText;
    private RequestManager mImgLoader;


    private String[] mImageSources;
    private int mCurPosition;
    private boolean mNeedSaveLocal;
    private boolean mNeedCookie;
    private boolean[] mImageDownloadStatus;


    public static void show(Context context, String images) {
        show(context, images, true);
    }


    public static void show(Context context, String images, String introduce, String title) {
        show(context, new String[]{images}, 0, true, false, introduce, title);
    }


    public static void show(Context context, String images, boolean needSaveLocal) {
        if (images == null) {
            return;
        }
        show(context, new String[]{images}, 0, needSaveLocal);
    }

    public static void show(Context context, String images, boolean needSaveLocal, boolean needCookie) {
        if (images == null) {
            return;
        }
        show(context, new String[]{images}, 0, needSaveLocal, needCookie, "", "");
    }

    public static void show(Context context, String[] images, int position) {
        show(context, images, position, true);
    }

    public static void show(Context context, String[] images, int position, boolean needSaveLocal) {
        show(context, images, position, needSaveLocal, false, "", "");
    }

    public static void show(Context context, String[] images, int position,
                            boolean needSaveLocal, boolean needCookie, String introduce, String title) {
        if (images == null || images.length == 0) {
            return;
        }
        if (images.length == 1 && !images[0].endsWith(".gif") && !images[0].endsWith(".GIF") && !needCookie) {
            if (TextUtils.isEmpty(introduce) && TextUtils.isEmpty(title)) {
                LargeImageActivity.show(context, images[0]);
            } else {
                LargeImageActivity.show(context, images[0], introduce, title);
            }
            return;
        }
        Intent intent = new Intent(context, ImageGalleryActivity.class);
        intent.putExtra(KEY_IMAGE, images);
        intent.putExtra(KEY_POSITION, position);
        intent.putExtra(KEY_NEED_SAVE, needSaveLocal);
        intent.putExtra(KEY_COOKIE, needCookie);
        context.startActivity(intent);
    }


    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_image_gallery;
    }

    @Override
    public void initViews() {

        getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        //设置权限管理
//        mRationale = new DefaultRationale();
//        mSetting = new PermissionSetting(this);
        Bundle bundle = getIntent().getExtras();
        mImageSources = bundle.getStringArray(KEY_IMAGE);
        mCurPosition = bundle.getInt(KEY_POSITION, 0);
        mNeedSaveLocal = bundle.getBoolean(KEY_NEED_SAVE, true);
        mNeedCookie = bundle.getBoolean(KEY_COOKIE, false);

        if (mImageSources != null) {
            // 初始化下载状态
            mImageDownloadStatus = new boolean[mImageSources.length];
        }

        setTitle("");

        mImagePager = (PreviewerViewPager) findViewById(R.id.vp_image);
        mIndexText = (TextView) findViewById(R.id.tv_index);

        mImagePager.addOnPageChangeListener(this);
        int len = mImageSources.length;
        if (mCurPosition < 0 || mCurPosition >= len) {
            mCurPosition = 0;
        }

        // If only one, we not need the text to show
        if (len == 1) {
            mIndexText.setVisibility(View.GONE);
        }

        mImagePager.setAdapter(new ViewPagerAdapter());
        mImagePager.setCurrentItem(mCurPosition);
        // First we call to init the TextView
        onPageSelected(mCurPosition);

    }


    private class ViewPagerAdapter extends PagerAdapter implements ImagePreviewView.OnReachBorderListener {

        private View.OnClickListener mFinishClickListener;

        @Override
        public int getCount() {
            return mImageSources.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = LayoutInflater.from(container.getContext())
                    .inflate(R.layout.lay_gallery_page_item_contener, container, false);
            ImagePreviewView previewView = (ImagePreviewView) view.findViewById(R.id.iv_preview);

//            TextView introduceText = (TextView) findViewById(R.id.tv_introduce);
//            TextView titleTxt = (TextView) findViewById(R.id.tv_title);
//            RelativeLayout introduceLayout = (RelativeLayout) findViewById(R.id.rl_introduce);

            previewView.setOnReachBorderListener(this);
            Loading loading = (Loading) view.findViewById(R.id.loading);
            ImageView defaultView = (ImageView) view.findViewById(R.id.iv_default);

            // Do load
            if (mNeedCookie) {
                loadImage(position, Utils.getGlideUrlByUser(mImageSources[position]),
                        previewView, defaultView, loading);
            } else {
                loadImage(position, mImageSources[position], previewView, defaultView, loading);
            }

            previewView.setOnClickListener(getListener());
            container.addView(view);
            return view;
        }

        private View.OnClickListener getListener() {
            if (mFinishClickListener == null) {
                mFinishClickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                };
            }
            return mFinishClickListener;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public void onReachBorder(boolean isReached) {
            mImagePager.isInterceptable(isReached);
        }

        private <T> void loadImage(final int pos, final T urlOrPath,
                                   final ImageView previewView,
                                   final ImageView defaultView,
                                   final Loading loading) {

            loadImageDoDownAndGetOverrideSize(urlOrPath, new DoOverrideSizeCallback() {
                @Override
                public void onDone(int overrideW, int overrideH, boolean isTrue) {
                    if (mImgLoader == null) {
                        mImgLoader = GlideApp.with(ImageGalleryActivity.this);
                    }
                    if (!isDestroy(ImageGalleryActivity.this)) {
                        //TODO 对照老代码查看对比一下
                        GlideRequest request = GlideApp
                                .with(ImageGalleryActivity.this)
                                .load(urlOrPath).listener(
                                        new RequestListener() {
                                            @Override
                                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                                                if (e != null) {
                                                    e.printStackTrace();
                                                }
                                                loading.stop();
                                                loading.setVisibility(View.GONE);
                                                defaultView.setVisibility(View.VISIBLE);
                                                updateDownloadStatus(pos, false);
                                                return false;
                                            }

                                            @Override
                                            public boolean onResourceReady(Object resource, Object model,
                                                                           Target target, DataSource dataSource, boolean isFirstResource) {
                                                loading.stop();
                                                loading.setVisibility(View.GONE);
                                                updateDownloadStatus(pos, true);
                                                return false;
                                            }
                                        });
                        // If download or get option error we not set override
                        if (isTrue && overrideW > 0 && overrideH > 0) {
                            request = request.override(overrideW, overrideH).fitCenter();
                        }
                        request.into(previewView);
                    }
                }
            });


        }

        private <T> void loadImageDoDownAndGetOverrideSize(final T urlOrPath, final DoOverrideSizeCallback callback) {
            if (mImgLoader == null) {
                mImgLoader = GlideApp.with(ImageGalleryActivity.this);
            }
            // In this save max image size is source
            final Future<File> future = mImgLoader.load(urlOrPath)
                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);

            Utils.runOnThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        File sourceFile = future.get();

                        BitmapFactory.Options options = BitmapUtil.createOptions();
                        // First decode with inJustDecodeBounds=true to checkShare dimensions
                        options.inJustDecodeBounds = true;
                        // First decode with inJustDecodeBounds=true to checkShare dimensions
                        BitmapFactory.decodeFile(sourceFile.getAbsolutePath(), options);

                        int width = options.outWidth;
                        int height = options.outHeight;
                        BitmapUtil.resetOptions(options);

                        if (width > 0 && height > 0) {
                            // Get Screen
                            final Point point = getDisplayDimens();

                            // This max size
                            final int maxLen = Math.min(Math.min(point.y, point.x) * 5, 1366 * 3);

                            // Init override size
                            final int overrideW, overrideH;

                            if ((width / (float) height) > (point.x / (float) point.y)) {
                                overrideH = Math.min(height, point.y);
                                overrideW = Math.min(width, maxLen);
                            } else {
                                overrideW = Math.min(width, point.x);
                                overrideH = Math.min(height, maxLen);
                            }

                            // Call back on main thread
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    callback.onDone(overrideW, overrideH, true);
                                }
                            });
                        } else {
                            // Call back on main thread
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    callback.onDone(0, 0, false);
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();

                        // Call back on main thread
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onDone(0, 0, false);
                            }
                        });
                    }
                }
            });
        }


    }


    @Override
    public void loadData(Bundle savedInstanceState) {

    }

    @Override
    public void onPageScrolled(int position, float v, int i1) {

    }

    @Override
    public void onPageSelected(int position) {

        mCurPosition = position;
        SpannableStringBuilder s = new com.blankj.utilcode.util.SpanUtils()
                .append((position + 1) + "")
                .setFontSize(28, true)
                .setForegroundColor(getResources().getColor(R.color.ui_config_color_red))
                .append("/" + mImageSources.length)
                .setFontSize(14, true).create();
        mIndexText.setText(s);
        // 滑动时自动切换当前的下载状态
        changeSaveButtonStatus(mImageDownloadStatus[position]);

    }


    private void updateDownloadStatus(int pos, boolean isOk) {
        mImageDownloadStatus[pos] = isOk;
        if (mCurPosition == pos) {
            changeSaveButtonStatus(isOk);
        }
    }


    private void changeSaveButtonStatus(boolean isShow) {
        if (mNeedSaveLocal) {
            findViewById(R.id.iv_save).setVisibility(isShow ? View.VISIBLE : View.GONE);
        } else {
            findViewById(R.id.iv_save).setVisibility(View.GONE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }


    private Point mDisplayDimens;

    @SuppressLint("ObsoleteSdkInt")
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    @SuppressWarnings("deprecation")
    private synchronized Point getDisplayDimens() {
        if (mDisplayDimens != null) {
            return mDisplayDimens;
        }
        Point displayDimens;
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        assert windowManager != null;
        Display display = windowManager.getDefaultDisplay();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            displayDimens = new Point();
            display.getSize(displayDimens);
        } else {
            displayDimens = new Point(display.getWidth(), display.getHeight());
        }

        // In this we can only get 85% width and 60% height
        //displayDimens.y = (int) (displayDimens.y * 0.60f);
        //displayDimens.x = (int) (displayDimens.x * 0.85f);

        mDisplayDimens = displayDimens;
        return mDisplayDimens;
    }


    interface DoOverrideSizeCallback {
        void onDone(int overrideW, int overrideH, boolean isTrue);
    }

    @Override
    public void onDestroy() {
        mImgLoader = null;
        super.onDestroy();
    }


    //判断Activity是否Destroy
    public static boolean isDestroy(Activity activity) {
        if (activity == null || activity.isFinishing() || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed())) {
            return true;
        } else {
            return false;
        }
    }

}
